package com.wisemoresystem.seal.service;

import com.wisemoresystem.seal.base.service.BaseService;
import com.wisemoresystem.seal.model.t_menu;
import com.wisemoresystem.seal.model.t_seal_type_config;
import com.wisemoresystem.seal.util.SpringTools;
import com.wisemoresystem.seal.util.json.JsonTools;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.omg.PortableServer.ForwardRequestHelper;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MenuService extends BaseService {

	public List<Map<String, Object>> selectRootMenuList() {
		String sql = "select * from t_menu t where t.status=0 and t.up_code='root' order by t.sort asc";
		List<Map<String, Object>> list = jt.queryForList(sql);

		return list;
	}

	public List<Map<String, Object>> selectRootMenuList(String auto) {
		String[] roles = auto.split(",");
		String codes = "";
		for (String string : roles) {
			codes += ",'" + string + "'";
		}
		auto = codes.replaceFirst(",", " ");

		String sql = "select * from t_menu t where t.status=0 and t.code in("
				+ auto + ") and t.up_code='root' order by t.sort asc";

		List<Map<String, Object>> list = jt.queryForList(sql);
		return list;
	}

	public List<Map<String, Object>> selectMenuList() {
		String sql = "select * from t_menu t where t.status=0 order by t.sort asc";
		List<Map<String, Object>> list = jt.queryForList(sql);
		return list;
	}

	public List<Map<String, Object>> selectMenuList(String auto) {
		String[] roles = auto.split(",");

		final List<String> params = new ArrayList<String>();
		for (String string : roles) {
			params.add(string);
		}

		final String hql = "from t_menu t where t.status=0 and t.code in(:codes) order by t.sort asc";

		List<t_menu> list = (List<t_menu>) ht
				.execute(new HibernateCallback<List<t_menu>>() {

					@Override
					public List<t_menu> doInHibernate(Session sn)
							throws HibernateException {
						Query query = sn.createQuery(hql);
						query.setParameterList("codes", params);
						return (List<t_menu>) query.list();

					}
				});
		List<Map<String, Object>> l = new ArrayList<Map<String, Object>>();
		for (t_menu t_menu : list) {
			Map<String, Object> map = JsonTools.jsonStrToMap(JsonTools
					.toJson(t_menu));
			l.add(map);
		}
		return l;
	}

	public List<Map<String, Object>> selectMenuListForRole() {

		String sql = "select t.* from t_menu t where t.status=0 order by t.sort asc";
		List<Map<String, Object>> list = jt.queryForList(sql);
		return list;
	}

	public static void main(String[] args) {
		MenuService s = (MenuService) SpringTools.getBean(MenuService.class);
		s.selectMenuList();
	}
}
